import axios, { AxiosError, AxiosResponse, InternalAxiosRequestConfig } from '@ohos/axios'
import { TOKEN } from '../common/model/commonType';
import { getToken } from '../utils/token'
import { router } from '@kit.ArkUI';

// 默认请求头
axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'

const service = axios.create({
  baseURL: 'localhost:8080',
  timeout: 6000,
})

// 请求拦截器
service.interceptors.request.use((config: InternalAxiosRequestConfig) => {
  // 是否需要设置 token
  // const isToken:boolean = false
  // if (config.headers) {
  //   isToken = (config.headers).isToken === false;
  // }
  if (getToken()) {
    config.headers['Authorization'] = 'Bearer ' + getToken(); // 让每个请求携带自定义token
  }
  return config;
}, (error: AxiosError) => {
  return Promise.reject(error)
})

// 响应拦截器
service.interceptors.response.use((response: AxiosResponse) => {
  // 未设置状态码则默认成功状态
  const code: number = response.data.code || 200;
  if (code == 401) {
    AlertDialog.show(
      {
        title: '会话已过期，请重新登录',
        subtitle: '',
        message: '',
        autoCancel: true,
        alignment: DialogAlignment.Center,
        gridCount: 4,
        showInSubWindow: true,
        isModal: true,
        offset: { dx: 0, dy: -20 },
        buttonDirection: DialogButtonDirection.HORIZONTAL,
        buttons: [
          {
            value: '确定',
            enabled: true,
            defaultFocus: true,
            style: DialogButtonStyle.HIGHLIGHT,
            action: () => {
              console.info('Callback when button3 is clicked')
              router.replaceUrl({
                url: 'pages/Login'
              })
            }
          },
        ],
        cancel: () => {
          console.info('Closed callbacks')
          router.replaceUrl({
            url: 'pages/Login'
          })
        },

      })
  }
  return response;
}, (error: AxiosError) => {
  return Promise.reject(error);
})

export default service;